<?php

namespace App\Http\Controllers\OA;

use App\Exceptions\BusinessException;
use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Logic\ProjectJsLogic;
use App\Http\Controllers\Logic\ProjectLogic;
use App\Http\Controllers\Logic\ProjectYsLogic;
use App\Http\Controllers\OATrait\OATrait;
use App\Http\Requests\ProjectLxRequest;
use App\Http\Requests\ProjectYsEditRequest;
use App\Http\Requests\ProjectYsRequest;
use App\Model\OAPartners;
use App\Model\OAPositionMapping;
use App\Model\OAProjectLx;
use App\Model\OAProjectYs;
use App\Model\OAProjectYsDetail;
use App\Model\OAShenPiLog;
use App\Model\OAStaff;
use App\Model\OATicket;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

/**
 * 立项相关
 */
class ProjectController extends Controller
{
    use OATrait;

    protected $logic;

    public function __construct()
    {
        $this->logic = new ProjectLogic();
    }

    //创建项目
    public function addProject(ProjectLxRequest $request)
    {
        $params = $this->mergeRequest($request);
        $params['create_role'] = $params['roleid'];
        try {
            $this->vaildateSameName($params);//提交检查
            $newXid = $this->logic->addNewProject($params);
            $action = Arr::get($params, 'is_save') ? "保存" : "提交";
            if ($newXid) ret_json('ok', $action . '成功', ['xmid' => $newXid]);
            else ret_json('err', $action . '失败');
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //过滤相同的下项目
    protected function vaildateSameName($params)
    {
        $info = OAProjectLx::query()
            ->where('name', $params['name'])
            ->when($xmid = Arr::get($params, 'xmid'), function ($q) use ($xmid) {
                return $q->where('id', "<>", $xmid);
            })
            ->exists();
        if ($info) throw new \Exception('存在相同的项目名称');
    }

    //查立项数据
    public function getProjectLx(Request $request)
    {
        $rules = [
            'name' => 'present|nullable|string',
            'created_user' => 'present|nullable|numeric',
            'batch_id' => 'present|nullable|string',
            'status' => 'present|nullable|in:0,1,2',
            'start' => 'present|nullable|date',
            'stop' => 'present|nullable|date',
            'page' => 'required|numeric|min:1',
            'page_size' => 'required|numeric|min:10'
        ];

        $this->verify($request->all(), $rules);

        $params = $this->mergeRequest($request);
        try {


            $list = $this->logic->getProjectLx($params);

            return ret_json('ok', '请求成功', $list);

        } catch (\Exception $e) {

            ret_json('err', $e->getMessage());
        }
    }

    //立项详情
    public function projectDetailLx(Request $request)
    {
        $rules = [
            'id' => 'required|exists:project_lx'
        ];
        $this->verify($request->all(), $rules);
        $params = $this->mergeRequest($request);
        $roleid = $params['roleid'];
        try {
            $data = $this->logic->projectDetailLx($params);
            $extendFiled = $this->getInfoExtend($data, $roleid);
            $data = json_decode(json_encode($data), true);
            $data['partners'] = OATicket::query()->where('status', 1)->select(['id', 'short_name as name'])->get()->toArray();
            $data = array_merge($data, $extendFiled);
            ret_json('ok', '请求成功', $data);

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //编辑立项数据
    public function editProjectLx(ProjectLxRequest $request, OAProjectLx $lx)
    {
        try {
            $params = $this->mergeRequest($request);
            $result = $this->logic->editProjectLx($params,$lx);
            $msg = operation(Arr::get($params, 'is_save'));
            if ($result) ret_json('ok', $msg . '成功');
            else ret_json('err', $msg . '失败');
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //修改供应商
    public function editProjectPartner(Request $request)
    {
        $rules = ['id' => 'required|exists:project_lx,id', 'partner_id' => 'required|numeric'];
        $this->verify($request->all(), $rules);
        try {
            $result = $this->logic->editProjectPartner($request->all());
            ret_json('ok', '客户名称修改成功');
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取预算下拉
    public function getYsList(Request $request)
    {
        try {
            $params = $this->mergeRequest($request);
            $list = $this->logic->getYsList($params);
            ret_json('ok', '请求成功', $list);
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取项目基本信息
    public function getProjectBaseInfo(Request $request)
    {
        $rules = ['id' => 'required|exists:project_lx'];

        $this->verify($request->all(), $rules);

        try {
            $info = $this->getBaseInfo($request->all());
            ret_json('ok', 'ok', $info);
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //添加预算数据
    public function addProjectYs(ProjectYsRequest $request)
    {

        try {
            if (empty($request->profit)) throw new \Exception('利润金额不能小于或等于0');
            $params = $this->mergeRequest($request);
            $logic = new ProjectYsLogic();
            $result = $logic->addProjectYs($params);
            $action = Arr::get($params, 'is_save') ? "保存" : "提交";
            if ($result) return success($action . '成功', ['ysid' => $result]);

            return error($action . '失败');

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取预算数据
    public function getProjectYsDetail(Request $request, OAProjectYs $projectYs)
    {
        //dd(admin(),admin_id(),roleid());
        try {
            $logic = new ProjectYsLogic();
            $info = $logic->getProjectYsDetail($projectYs);
            $roleid = roleid();
            $uid = admin_id();
            $info->project = [
                'total' => fomateMoney(0, $info->total),
                'tax' => fomateMoney(0, $info->tax),
                'profit' => fomateMoney(0, $info->profit),
                'percent' => $info->percent,
                'desc' => $info->desc,
                'sub_total' => fomateMoney(0, $info->sub_total),
                'is_add' => $info->uid == $uid && $info->is_save,
                'offer' => fomateMoney(0, $info->offer),
                'cost' => fomateMoney(0, $info->cost),
            ];
            $extend = $this->getInfoExtend($info, $roleid);
            $info = json_decode(json_encode($info), true);
            $info = array_merge($extend, $info);
            $info['is_show'] = $roleid == Constant::ROLE_CAIGOU;
            $info['is_add'] = !Arr::get($extend, 'disable');
            if ($info['is_show']) $info['seller_list'] = OAStaff::query()->whereRaw('FIND_IN_SET (213,roleid)')->select(['id', 'username'])->get()->toArray();
            ret_json('ok', 'ok', $info);

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取预算审批列表
    public function getProjectYsList(Request $request)
    {
        $rules = [
            'page' => 'required|min:1|numeric',
            'page_size' => 'required|min:10|numeric',
            'batch_id' => 'present|nullable|array',
            'create_user' => 'present|nullable|array',
            'name' => 'present|nullable|string',
            'status' => 'present|nullable|in:0,1,2,3',
            'date' => 'present|date|nullable|array',
            'type' => 'required|in:1,2'
        ];

        try {
            $params = $this->mergeRequest($request);
            $this->verify($params, $rules);
            $this > $this->checkHeader($request->header());
            $logic = new ProjectYsLogic();
            $list = $logic->getProjectYsList($params);

            ret_json('ok', 'ok', $list);

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //编辑预算数据
    public function editProjectYs(ProjectYsEditRequest $request, OAProjectYs $ys)
    {
        try {
            $this->checkHeader($request->header());
            $params = $this->mergeRequest($request);
            if ($params['roleid'] == 212 && !$request->is_save) {
                if ($request->filled('seller_id') && empty($request->seller_id)) throw new \Exception('销售经理不能为空');
            }
            $info = (new ProjectYsLogic())->editProjectYs($request,$ys);
            $is_save = Arr::get($params, 'is_save', 0);
            $operation = $is_save ? "保存" : (isPM() ? "提交" : "立即修改");
            if ($info) ret_json('ok', $operation . '预算成功');
            else ret_json('err', $operation . '预算失败');

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //更新销售经理
    public function updateSeller(Request $request, OAProjectYs $ys)
    {
        $rules = ['seller_id' => 'required|exists:staff,id'];
        try {
            $this->verify($request->all(), $rules);

            $result = (new ProjectYsLogic())->updateSeller($request, $ys);

            if ($result) ret_json('ok', '修改成功');

            else ret_json('err', '修改失败');

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取结算下拉框
    public function getProjectJsSelect(Request $request)
    {
        try {
            $params = $this->mergeRequest($request);
            $list = (new ProjectJsLogic())->getProjectJsSelect($params);
            ret_json('ok', '请求成功', $list);
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取结算数据
    public function getProjectJsData(Request $request)
    {
        $rules = [
            'id' => 'required|exists:project_lx,id',
            'ysid' => 'required|exists:project_ys,id'
        ];
        try {
            $params = $this->mergeRequest($request);
            $this->verify($params, $rules);
            $projectYs = OAProjectYs::query()->find($request->input('ysid'));
            $info = (new ProjectJsLogic())->getProjectJsData($projectYs);
            ret_json('ok', '请求成功', $info);
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //保存结算数据
    public function saveProjectData(Request $request)
    {
        $rules = [
            'xmid' => 'required|exists:project_lx,id',
            'js' => 'required|array',
            'is_save' => 'required|in:0,1|numeric',
            'ysid' => 'sometimes|numeric|nullable',
            'newJs' => 'required|array',
            'costList' => 'present|array|nullable',
        ];
        $params = $this->mergeRequest($request);
        $this->verify($params, $rules);
        $logic = new ProjectJsLogic();
        $result = $logic->saveProjectData($params);
        $msg = $params['is_save'] ? '保存成功' : '提交成功';
        ret_json('ok', $msg, $result);

    }

    //获取结算数据详情
    public function getJsDetail(Request $request, OAProjectYs $projectJs)
    {
        try {
            $params = $this->mergeRequest($request);
            $project = (new ProjectJsLogic())->getJsDetail($params, $projectJs);
            ret_json('ok', '请求成功', $project);
        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //编辑结算
    public function editProjectJs(Request $request, OAProjectYs $projectJs)
    {
        $rules = [
            'js' => 'required|array',
            'costList' => 'required|array',
            'newJs' => 'sometimes|array',
            'is_save' => 'required|in:0,1|numeric',
        ];
        try {
            $params = $this->mergeRequest($request);
            $this->verify($params, $rules);
            (new ProjectJsLogic())->saveProjectData($params, $projectJs);
            $isSave = $request->input("is_save");
            if ($isSave) {
                $action = "保存";
            } else {
                $action = $params['roleid'] == $projectJs->create_role ? '提交' : '立即修改';
            }
            ret_json('ok', $action . '成功');
        } catch (\Exception $e) {
            dump($e);
            ret_json('err', $e->getMessage());
        }
    }

    //删除项目
    public function delProject(Request $request)
    {
        try {
            $rules = [
                'id' => 'required',
                'type' => 'required|string'
            ];

            $this->verify($request->all(), $rules);
            $params = $this->mergeRequest($request);
            //dd($params);
            $this->logic->delProject($params);

            ret_json('ok', '删除成功');

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    //获取预算数据
    public function getYsData(Request $request)
    {
        try {
            $rules = [
                'id' => 'required|exists:project_ys,id',
            ];
            $this->verify($request->all(), $rules);

            $data = (new ProjectYsLogic())->getYsData($request->all());
            ret_json('ok', 'ok', $data);

        } catch (\Exception $e) {
            ret_json('err', $e->getMessage());
        }
    }

    public function calculateProfit(Request $request)
    {
        $offer = $request->input("offer", '0.00');
        $offer = resetMoney($offer);
        $rate = $request->input("rate", '0.00');
        $tax = bcmul($offer, $rate, 2);
        $sub_total = '0.00';
        $ysData = $request->input("ysData", []);
        $newJs = $request->input("newJs", []);
        $ysid = $request->input('ysid', 0);
        //预算
        foreach ($ysData as $ys) {
            $is_del = Arr::get($ys, 'is_del', 0);
            if ($ys['paytype'] == Constant::PAY_TYPE_YJ || $is_del) continue;
            $sub_total = bcadd($sub_total, resetMoney($ys['money']), 2);
        }
        //新加结算
        if ($newJs) {
            foreach ($newJs as $js) {
                $jsmoney = Arr::get($js, 'jsmoney', '0.00');
                //dd($jsmoney);
                $sub_total = bcadd($sub_total, resetMoney($jsmoney), 2);
            }
        }
        $total = bcadd($sub_total, $tax, 2);
        $profit = bcsub($offer, $total, 2);
        $percent = $offer > 0 ? bcdiv($profit, $offer, 4) : '0.00';
        $percent = bcmul($percent, '100', 2);
        if ($ysid) {
            $ys = OAProjectYs::query()->find($ysid);
            if ($ys) {
                $ys->cost = $total;
                $ys->tax = $tax;
                $ys->profit = $profit;
                $ys->total = $total;
                $ys->percent = $percent;
                $ys->offer = $offer;
                $ys->save();
            }
        }

        $sub_total = fomateMoney("", $sub_total);
        $tax = fomateMoney("", $tax);
        $profit = fomateMoney("", $profit);
        $cost = $total = fomateMoney("", $total);
        $ysmoney = fomateMoney("", $offer);
        $data = compact('sub_total', 'profit', 'percent', 'total', 'tax', 'profit', 'cost', 'ysmoney');
        ret_json('ok', 'ok', $data);
    }

    public function delYsDetail(Request $request, OAProjectYsDetail $ysDetail)
    {
        $ys = $ysDetail->ys;
        //dd($ys);
        $roleList = $ys->roles;
        //dd(roleid(),$roleList);
        if (!in_array(roleid(), $roleList)) {
            // dd($roleList,roleid());
            throw new BusinessException("无权限删除");
        }
        $uids = $ys->uids;
        if (!in_array(admin_id(), $uids)) {
            throw new BusinessException("uid无权限删除");
        }
        $ys->is_save = Constant::STATUS_ON;
        $ys->save();
        $ysDetail->is_del = Constant::STATUS_ON;
        $ysDetail->save();
        return success("删除成功");
    }

    public function reCalculateYsProfit(Request $request, OAProjectYs $ys)
    {
        $ysData = $request->input('ys', []);
        foreach ($ysData as $key => $val) {
            if ($key != "percent") $ysData[$key] = resetMoney($val);
        }
        $ys->fill($ysData)->save();
        return success("success");
    }


}
